package com.wuhao.jdqlib.utils;

import android.util.Log;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;

/**
 * Created: Lpz
 * Date: 2024/10/29
 * Description:
 */
public class DataUtils {
    public static String bytesToHexString(byte[] bytes) {
        if (bytes == null) return "";
        StringBuilder str = new StringBuilder();
        for (byte b : bytes) {
            str.append(String.format("%02X", b));
        }
        return str.toString();
    }


    public static byte[] hexStrToBytes(String hexString) {
        int len = hexString.length();
        byte[] data = new byte[len / 2];
        for (int i = 0; i < len; i += 2) {
            data[i / 2] = (byte) ((Character.digit(hexString.charAt(i), 16) << 4)
                    + Character.digit(hexString.charAt(i + 1), 16));
        }
        return data;
    }

    /// <returns>从给定的四个字节转换得到的整数。</returns>
    public static int BytesToIntBigEndian(byte[] data, int index)
    {
        // 确保不会越界
        if (index < 0 || index + 3 >= data.length) {
            throw new IllegalArgumentException("Index out of bounds.");
        }

        return ((data[index] & 0xFF) << 24) |
                ((data[index + 1] & 0xFF) << 16) |
                ((data[index + 2] & 0xFF) << 8) |
                (data[index + 3] & 0xFF);
    }

    /**
     * 计算CRC16校验码
     *
     * @param data 字节数组
     * @return {@link String} 校验码
     * @since 1.0
     */
    public static byte[] crc_16(byte[] data) {
        Log.d("lpz", "crc_16: data=" + byte2HexStr(data) + " length=" + data.length);
        int CRC = 0x0000ffff;
        int POLYNOMIAL = 0x0000a001;
        int i, j;
        byte[] Rcvbuf = new byte[2];

        if (data.length <= 0) {
            CRC = 0;
        } else {
            for (i = 0; i < data.length; i++) {
                CRC ^= ((int) data[i] & 0x000000ff);
                for (j = 0; j < 8; j++) {
                    if ((CRC & 0x00000001) != 0) {
                        CRC >>= 1;
                        CRC ^= POLYNOMIAL;
                    } else {
                        CRC >>= 1;
                    }
                }
            }
        }
        Rcvbuf[0] = (byte) (CRC & 0x00ff);  //高位置
        Rcvbuf[1] = (byte) (((CRC & 0xff00) >> 8) & 0x00FF);//低位置
        return Rcvbuf;
    }

    /**
     * short转换为字节
     *
     * @param s
     * @return
     */
    public static byte[] shortToByteArray(short s) {
        byte[] targets = new byte[2];
        // for (int i = 0; i < 2; i++) {
        // int offset = (targets.length - 1 - i) * 8;
        // targets[i] = (byte) ((s >>> offset) & 0xff);
        // }
        targets[0] = (byte) (s & 0x00ff);
        targets[1] = (byte) ((s & 0xff00) >> 8);
        return targets;
    }

    /**
     * 将float值转换为4字节的byte数组
     *
     * @param f 需要转换的float值
     * @return 包含4个字节的byte数组
     */
    public static byte[] floatToByteArray(float f) {
        return ByteBuffer.allocate(4).order(ByteOrder.BIG_ENDIAN).putFloat(f).array();
    }


    public static byte[] shortToByteArrayBigEndian(short s) {
        return new byte[] {
                (byte) (s >> 8), // High byte
                (byte) (s & 0xFF) // Low byte
        };
    }

    /**
     * int 类型的数值转换为 byte[] 数组 大端字序
     * @param value
     * @return
     */
    public static byte[] intToByteArrayBigEndian(int value) {
        return new byte[] {
                (byte) (value >>> 24), // 最高字节
                (byte) (value >>> 16), // 次高字节
                (byte) (value >>> 8),  // 次低字节
                (byte) value           // 最低字节
        };
    }


    public static short byteArrayToShortBigEndian(byte[] bytes, int idx) {
        return (short) ((bytes[idx] << 8) | (bytes[idx + 1] & 0xff));
    }

    /**
     * bytes转换成十六进制字符串
     *
     * @return String 每个Byte值之间空格分隔
     */
    public static String byte2HexStr(byte[] b) {
        if(b == null)
            return "";
        String stmp = "";
        StringBuilder sb = new StringBuilder("");
        for (int n = 0; n < b.length; n++) {
            stmp = Integer.toHexString(b[n] & 0xFF);
            sb.append((stmp.length() == 1) ? "0" + stmp : stmp);
            // sb.append(" ");
        }
        return sb.toString().toUpperCase().trim();
    }

    /**
     * 将十六进制字符串转换为float值
     *
     * @param hexString 十六进制字符串
     * @return 转换得到的float值
     */
    public static float hexStringToFloat(String hexString) {
        // 字符串转换为字节数组
        byte[] bytes = new byte[hexString.length() / 2];
        for (int i = 0; i < hexString.length(); i += 2) {
            bytes[i / 2] = (byte) ((Character.digit(hexString.charAt(i), 16) << 4)
                    + Character.digit(hexString.charAt(i + 1), 16));
        }

        // 字节数组转换为float
        return ByteBuffer.wrap(bytes).order(ByteOrder.BIG_ENDIAN).asFloatBuffer().get();
    }

    /**
     * 将字节数组转换为float值，并使用大端字序
     *
     * @param bytes 包含float值的字节数组
     * @return 转换得到的float值
     */
    public static float byteArrayToFloatBigEndian(byte[] bytes) {
        if (bytes.length != 4) {
            throw new IllegalArgumentException("The byte array must be exactly 4 bytes long.");
        }
        return ByteBuffer.wrap(bytes).order(ByteOrder.BIG_ENDIAN).asFloatBuffer().get();
    }

}
